<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
		<uni-forms err-show-type="toast" ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
			<!--调拨单信息-->
			<view class="detail-item">
				<uni-section title="调拨单信息" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms-item label="出货仓库" name="formWarehouseId" required>
						<uni-data-select
							v-model="formData.formWarehouseId"
							placeholder="请选择出货仓库"
							@change="changeFormWarehouseId"
							:localdata="warehouseList"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="目的仓库" name="destinationWarehouseId" required>
						<uni-data-select
							v-model="formData.destinationWarehouseId"
							placeholder="请选择目的仓库"
							@change="changeDestinationWarehouseId"
							:localdata="warehouseList"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="收货人" name="destinationUserId" required style="display: none;">
						<uni-easyinput disabled v-model="formData.destinationUserId" placeholder="收货人" />
					</uni-forms-item>
					<uni-forms-item label="收货人" name="destinationUserName" required>
						<uni-easyinput disabled v-model="formData.destinationUserName" placeholder="收货人" />
					</uni-forms-item>
				</view>
			</view>
			
			<!--商品清单-->
			<view class="detail-item">
				<view class="main-flex">
					<uni-section title="商品清单" type="line"></uni-section>
					<!--操作-->
					<view class="operate main-flex">
						<up-button
							class="operate-btn main-flex"
							size="mini"
							type="primary"
							@click="addFun">
							<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
							<view class="operate-btn-text">新增</view>
						</up-button>
					</view>
				</view>
				<view class="detail-content table">
					<ty-table
						:data="chooseProductList"
						:columns="columns"
						:sortable="true"
						:cellClassName="() => 'table-cell'"
						:headerCellClassName="() => 'table-cell'"
						:rowClassName="() => 'table-row'"
						stripe
						border>
						<template v-slot:table1="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex" style="overflow: hidden;">
									商品：
									<text class="table-td-text main-flex-item">{{row.productName}}</text>
								</view>
								<view class="table-td-row main-flex">
									批次：
									<text class="table-td-text main-flex-item">{{row.batchNumber}}</text>
								</view>
								<view class="table-td-row main-flex">
									规格：
									<uni-tag size="small" type="success" :text="row.moreSpec === 0 ? '单规格' : '多规格'" />
								</view>
								<view class="table-td-row main-flex">
									生产：
									<text class="table-td-text price">{{row.productionDate}}</text>
								</view>
								<view class="table-td-row main-flex">
									过期：
									<text class="table-td-text price">{{row.expireDate}}</text>
								</view>
							</view>
						</template>
						<template v-slot:table2="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex">
									数量：
									<text class="table-td-text price">{{row.number}}</text>
								</view>
								<view class="table-td-row main-flex">
									调拨：
									<view class="table-td-input">
										<uni-number-box :min="1" :max="row.number" @change="changeAllocationNumber($event, row)" background="#007aff" color="#ffffff" v-model="row.allocationNumber" ></uni-number-box>
									</view>
								</view>
								<view class="table-td-row main-flex">
									<view class="operate">
										<up-button
											class="operate-btn main-flex"
											size="mini"
											type="error"
											@click="delFun(row)">
											<uni-icons class="operate-btn-icon" type="trash" size="28rpx" color="#ffffff"></uni-icons>
											<view class="operate-btn-text">删除</view>
										</up-button>
									</view>
								</view>
							</view>
						</template>
						<template v-slot:empty>
							<view class="table-empty">
								<up-empty mode="data"/>
							</view>
						</template>
					</ty-table>
				</view>
				
				<uni-section title="调拨备注" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms-item label="调拨说明" name="remark">
						<uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入调拨说明"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="金额" name="allPrice" style="display: none;">
						<uni-easyinput type="number" v-model="formData.allPrice" placeholder="请输入金额"></uni-easyinput>
					</uni-forms-item>
				</view>
				
			</view>
			
			<view class="formRef-btn">
				<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
			</view>
			</uni-forms>
		</view>
		
		<!--商品选择-->
		<ty-storage-product-self 
			:showProduct="showProduct"
			:warehouseId="formData.formWarehouseId"
			@change="changeProduct"
			@close="closeProduct">
		</ty-storage-product-self>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import { timeFormat } from 'uview-plus'
import { warehouseAllocationEdit } from "@/api/erp_api/warehouse"
import { warehouse } from "@/api/erp_api/warehouse"
import useSetStore from '@/store/modules/set'
import { Decimal } from 'decimal.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	onLoad((option) => {
		getAllWarehouse()
	})
	
	// 获取仓库
	const warehouseList = ref([])
	const warehouseDeliveryList = ref([])
	const getAllWarehouse = () => {
		warehouse().then(res => {
			warehouseList.value = res.rows.filter(item => item.status === 0).map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	
	// 选择发货仓库
	const changeFormWarehouseId = (e) => {
		
	}
	// 选择目的仓库
	const changeDestinationWarehouseId = (e) => {
		const filter = warehouseList.value.filter(item => item.id === e)
		formData.value.destinationUserName = filter?.[0]?.userName || ''
		formData.value.destinationUserId = filter?.[0]?.userId || ''
	}
	
	// 选择的商品
	const chooseProductList = ref([])
	// 表格头部
	const columns = ref([
		{ title: '商品信息', key: 'table1' },
		{ title: '调拨数量', key: 'table2', width: '140px' }
	])
	
	// form表单数据
	const formData = ref({
		allPrice: 0,
		destinationUserName: '',
		destinationUserId: '',
		destinationWarehouseId: '',
		formWarehouseId: '',
		remark: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		destinationWarehouseId: {
			rules: [{ required: true, errorMessage: '请选择目的仓库' }]
		},
		formWarehouseId: {
			rules: [{ required: true, errorMessage: '请选择发货仓库' }]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			const productList = chooseProductList.value.filter(item => Number(item.allocationNumber) > 0).map(item => {
				return {
					...item
				}
			})
			if (productList.length === 0) {
				return uni.$u.toast('商品不能为空')
			}
			const params = { 
				...formRes,
				productList
			}
			isSubmit.value = true
			warehouseAllocationEdit(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				setStore.purchaseOrder = {}
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			allPrice: 0,
			destinationUserName: '',
			destinationUserId: '',
			destinationWarehouseId: '',
			formWarehouseId: '',
			remark: ''
		}
	}
	const changeAllocationNumber = (e, row) => {
		chooseProductList.value[row.rowIndex].allocationNumber = e
	}
	// 商品选择
	const showProduct = ref(false)
	const addFun = () => {
		if (!formData.value.formWarehouseId) return uni.$u.toast('请选择发货仓库')
		showProduct.value = true
	}
	const closeProduct = () => {
		showProduct.value = false
	}
	const changeProduct = (list) => {
		for(let i = 0; i < list.length; i++) {
			const filter = chooseProductList.value.find(item => item.productId === list[i].productId)
			if (!filter) {
				chooseProductList.value.push({
					allocationNumber: 1,
					...list[i]
				})
			}
		}
	}
	// 删除商品
	const delFun = (row) => {
		chooseProductList.value.splice(row.rowIndex, 1)
	}
	
</script>

<style scoped lang="scss">
	.search {
		margin-top: 0;
	}
	.table-td-input {
	}
	.price {
		font-size: 28rpx;
	}
	.operate {
		margin-left: auto;
	}
	:deep(.table-cell) {
		&:last-child {
			align-self: center;
		}
	}
	.formRef-btn {
		padding: 0rpx 20rpx 40rpx;
	}
</style>
